#include "GraphicalComposite.h"

GraphicalComposite::GraphicalComposite()
{
}

GraphicalComposite::GraphicalComposite(long id)
        : GraphicalElement(id)
{
    children.clear();
}

void GraphicalComposite::render(const Position& parent)
{
    GraphicalElement::render(parent);
    for (Children::iterator it = children.begin(); it != children.end(); ++it)
    {
        (*it)->render(parent.move(getPosition()));
    }
}

void GraphicalComposite::traverse(const Event& event)
{
    GraphicalElement::traverse(event);
    for (Children::iterator it = children.begin(); it != children.end(); ++it)
    {
        (*it)->traverse(event);
    }
}

void GraphicalComposite::addChild(GraphicalElement* element)
{
    children.push_back(element);
}

void GraphicalComposite::update(unsigned long tick)
{
    GraphicalElement::update(tick);
    for (Children::iterator it = children.begin(); it != children.end(); ++it)
    {
        (*it)->update(tick);
    }
}

void GraphicalComposite::eraseChildren()
{
    for (Children::iterator it = children.begin(); it != children.end(); ++it)
    {
        delete (*it);
    }
    children.clear();
}

void GraphicalComposite::removeChild(long idToRemove, bool deleteIt)
{
    for (Children::iterator it = children.begin(); it != children.end(); ++it)
    {
        if ((*it)->getId() == idToRemove)
        {
            if (deleteIt)
            {
                delete (*it);
            }
            children.erase(it);
            return;
        }
    }
}

GraphicalElement* GraphicalComposite::findChild(long idToFind)
{
    for (Children::iterator it = children.begin(); it != children.end(); ++it)
    {
        if ((*it)->getId() == idToFind)
        {
            return (*it);
        }
    }
    return NULL;
}

GraphicalComposite::~GraphicalComposite()
{
    eraseChildren();
}

